<template>
  <div class="user-management-view" v-loading="loading">
    <div class="management-tree-view" v-show="showTree">
      <el-tree style="flex: 1" :data="treeData" :props="treeProps" node-key="id" default-expand-all :expand-on-click-node="false" @node-click="handleNodeClick"></el-tree>
    </div>
    <div class="tree-arrow-view" @click="showTree = !showTree">
      <div class="arrow-view"><i :class="showTree ? 'el-icon-caret-left' : 'el-icon-caret-right'"></i></div>
    </div>
    <div class="table-data-view" v-loading="tableLoading">
      <div class="common-screen-view">
        <div class="common-screen-cell">
          <!-- <div class="common-screen-title" style="width:80px">{{$t('user_management.account')}}：</div> -->
          <el-input v-model="name" :placeholder="$t('user_management.account')"></el-input>
        </div>
        <div class="common-screen-cell">
          <!-- <div class="common-screen-title" style="width:100px">{{$t('user_management.reg_time')}}：</div> -->
          <el-date-picker v-model="dates" type="daterange" range-separator="-" :start-placeholder="$t('user_management.start_time')" :end-placeholder="$t('user_management.end_time')" value-format="yyyy-MM-dd"> </el-date-picker>
        </div>
        <el-button type="primary" icon="el-icon-search" @click="searchUserList">{{ $t('global.search') }}</el-button>
        <el-button type="primary" icon="el-icon-plus" v-if="checkPerm('mgr_add')" @click="addUser">{{ $t('global.add') }}</el-button>
        <el-button type="primary" icon="el-icon-folder-opened" @click="exportData">{{ $t('global.export') }}</el-button>
      </div>
      <table-list ref="tableView" class="table-list-view" :tableConfig="tableConfig" :tableData="tableData" @reviseUser="reviseUser" @delUser="delUser" @handleSwitch="handleSwitch" @setRole="setRole" @resetPassword="resetPassword"></table-list>
      <table-pagination :total="count" :currentPage="pageNow" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"> </table-pagination>
    </div>

    <el-dialog :title="$t('user_management.edit_user_info')" :close-on-click-modal="false" :visible.sync="userInfoVisible" width="600px">
      <add-edit-user :isEdit="isEdit" :editUserInfo="editUserInfo" :treeData="treeData" @cancelView="cancelView" @refreshData="refreshData"></add-edit-user>
    </el-dialog>

    <el-dialog :title="$t('tables_title.assign_roles')" :close-on-click-modal="false" :visible.sync="userRoleVisible" width="400px">
      <set-roles-view :roleIds="roleIds" :userId="roleUserId" @refreshData="refreshData"></set-roles-view>
    </el-dialog>
  </div>
</template>

<script>
import { getMgrList, delMgrUser, resetUserPassword, changeUserStatus } from '@/api/userApi.js'
import { getTreeNowUser } from '@/api/deptApi.js'

import { checkPermission } from '@/common/utils/permission.js'
import { getDeptTreeData, exportToExcel } from '@/common/utils/util.js'

export default {
  data() {
    return {
      isEdit: false,
      showTree: true,
      editUserInfo: {},
      loading: false,
      tableLoading: false,
      userInfoVisible: false, //新增编辑用户弹窗控制
      userRoleVisible: false, //分配用户角色
      tableConfig: {}, //table的基本配置
      tableData: [], //table数据源
      pageSize: 10, //每页查询数量
      count: 0, //总数
      pageNow: 1, //当前页码
      treeData: [], //树形数据
      treeProps: {
        children: 'children',
        label: 'name',
      },
      dates: [],
      deptId: 0, //部门id 默认查询全部
      name: '', //名称
      timeLimit: '', //注册时间
      roleIds: '', //角色IDs
      roleUserId: '', //需要修改的角色的用户ID
    }
  },
  components: {
    tableList: () => import('@/components/common_tables.vue'), //引入table组件
    tablePagination: () => import('@/components/table_pagination.vue'), //引入页码组件   为方便拓展 把它与table组件分开封装
    addEditUser: () => import('./add_edit_user.vue'),
    setRolesView: () => import('./set_roles.vue'),
  },
  created() {
    this.tableConfig = {
      isCheckBox: true,
      props: [
        { type: 'text', label: 'tables_title.account', prop: 'account' },
        { type: 'text', label: 'tables_title.name', prop: 'name' },
        { type: 'text', label: 'tables_title.dept', prop: 'deptName' },
        { type: 'text', label: 'tables_title.position', prop: 'positionName' },
        { type: 'text', label: 'tables_title.phone', prop: 'phone' },
        { type: 'text', label: 'tables_title.create_time', prop: 'createTime' },
        { type: 'switch', label: 'tables_title.status', prop: 'state', callback: 'handleSwitch', width: 100 },
      ],
      isOpt: true,
      optBtns: [
        { label: 'global.modify', callback: 'reviseUser', code: 'mgr_edit' },
        { label: 'global.delete', callback: 'delUser', code: 'mgr_delete' },
        { label: 'tables_title.assign_roles', callback: 'setRole', code: 'mgr_setRole' },
        { label: 'tables_title.reset_password', callback: 'resetPassword', code: 'mgr_reset' },
      ],
    }
    this.getTreeNowUserList()
  },
  methods: {
    getTreeNowUserList() {
      //获取所有部门列表
      this.loading = true
      getTreeNowUser()
        .then((res) => {
          this.loading = false
          if (res.status == 200) {
            this.treeData = getDeptTreeData(res.data)
            if (this.treeData.length > 0) {
              this.getMgrInfoList()
            }
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message.error(e.message)
        })
    },
    checkPerm(code) {
      //校验权限
      return checkPermission(code)
    },
    getMgrInfoList() {
      //获取管理用户列表
      this.tableLoading = true
      getMgrList({
        deptId: this.deptId,
        name: this.name,
        timeLimit: this.timeLimit,
        page: this.pageNow,
        limit: this.pageSize,
      })
        .then((res) => {
          this.tableLoading = false
          if (res.status == 200) {
            this.count = res.data.count
            res.data.data.forEach((element) => {
              element.state = element.statusName == '启用'
            })
            this.tableData = res.data.data
          }
        })
        .catch((e) => {
          this.tableLoading = false
          this.$message.error(e.message)
        })
    },
    searchUserList() {
      //搜索用户
      this.pageNow = 1
      console.log(this.dates)
      if (this.dates != null && this.dates.length > 1) {
        this.timeLimit = this.dates.join(' - ')
      } else {
        this.timeLimit = ''
      }
      this.getMgrInfoList()
    },
    handleNodeClick(data) {
      //树形节点点击触发事件
      // console.log(data)
      this.deptId = data.id
      this.pageNow = 1
      this.getMgrInfoList()
    },
    handleSizeChange(val) {
      //修改每页的显示条数
      this.pageSize = val
      this.pageNow = 1
      this.getMgrInfoList()
    },
    handleCurrentChange(val) {
      //切换当前页码
      this.pageNow = val
      this.getMgrInfoList()
    },
    addUser() {
      //新增用户
      this.editUserInfo = {}
      this.isEdit = false
      this.userInfoVisible = true
    },
    reviseUser(row) {
      //修改用户信息
      this.editUserInfo = row
      this.isEdit = true
      this.userInfoVisible = true
    },
    delUser(row) {
      //删除用户操作
      console.log(row)
      this.$confirm('是否删除用户"' + row.account + '"?', this.$t('global.tips'), {
        confirmButtonText: '确定',
        cancelButtonText: this.$t('global.cancel'),
        type: 'warning',
      })
        .then(() => {
          delMgrUser({ userId: row.userId }).then((res) => {
            console.log(res)
            if (res.data.code == 200) {
              this.$message({
                message: this.$t('global.del_success'),
                type: 'success',
              })
              this.pageNow = 1
              this.getMgrInfoList()
            } else {
              this.$message.error(res.data.message)
            }
          })
        })
        .catch(() => {})
    },
    resetPassword(row) {
      //重置密码
      this.$confirm(this.$t('user_management.reset_pwd'), this.$t('global.tips'), {
        confirmButtonText: this.$t('global.confirm'),
        cancelButtonText: this.$t('global.cancel'),
        type: 'warning',
      })
        .then(() => {
          resetUserPassword({ userId: row.userId }).then((res) => {
            if (res.data.code == 200) {
              this.$message({
                message: this.$t('global.modified_success'),
                type: 'success',
              })
            } else {
              this.$message.error(res.data.message)
            }
          })
        })
        .catch(() => {})
    },
    setRole(row) {
      //设置用户角色
      this.roleIds = row.roleId
      this.roleUserId = row.userId
      this.userRoleVisible = true
    },
    handleSwitch(row) {
      //status :freeze(冻结用户),unfreeze(解除冻结)
      let formData = new FormData()
      formData.append('status', row.state ? 'unfreeze' : 'freeze')
      formData.append('userId', row.userId)
      this.loading = true
      changeUserStatus(formData)
        .then((res) => {
          this.loading = false
          if (res.status != 200) {
            this.$message.error(res.data.message)
          }
          this.getMgrInfoList()
        })
        .catch((e) => {
          this.loading = false
          this.getMgrInfoList()
        })
    },
    cancelView() {
      //关闭编辑用户弹窗
      this.userInfoVisible = false
    },
    refreshData() {
      //刷新表格数据
      this.userRoleVisible = false
      this.userInfoVisible = false
      this.page = 1
      this.getMgrInfoList()
    },
    exportData() {
      let exportData = this.$refs.tableView.getCheckList()
      if (exportData.length == 0) {
        this.$message({
          message: this.$t('global.select_export'),
          type: 'warning',
        })
        return
      }
      let columns = [
        { title: this.$t('tables_title.account'), key: 'account' },
        { title: this.$t('tables_title.name'), key: 'name' },
        { title: this.$t('tables_title.dept'), key: 'deptName' },
        { title: this.$t('tables_title.position'), key: 'positionName' },
        { title: this.$t('tables_title.phone'), key: 'phone' },
        { title: this.$t('tables_title.create_time'), key: 'createTime' },
        { title: this.$t('tables_title.status'), key: 'statusName' },
      ]
      exportToExcel(columns, exportData, this.$t('global.table_data_title')) //表头 导出数据 文件名
    },
  },
}
</script>

<style lang="scss" scoped>
.user-management-view {
  width: 100%;
  height: 100%;
  display: flex;
}
</style>
